package org.openlab.model;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;

import lombok.Data;
import lombok.EqualsAndHashCode;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

@Data
@EqualsAndHashCode(callSuper=false)
@Entity
@Table(name = "ExchangeMapping")
public class ExchangeMapping extends BaseEntity  {
	private static final long serialVersionUID = 6535337197718086015L;
	public static final Function<ExchangeMapping, String> FUNCTION_EXID = new Function<ExchangeMapping, String>() {
		@Override
		public String apply(ExchangeMapping ex) {
			return ex.getExId();
		}
	};
	
	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	private long id;
	@Column(nullable = false)
	private String exId;
	@Column(nullable = false)
	private String docId;
	@Column(nullable = false)
	private String revision;	
	
	private String sender;
	@Column(nullable = false)
	private String fromTable;
	@Column(nullable = false)
	private String receiver;
	@Column(nullable = false)
	private String toTable;
	@Column(nullable = false)
	private String commodity;
	
	@Column(nullable = false, columnDefinition = "bigint default 0")
	private int status;
	@Column(nullable = true)
	private String note;
	@Column(nullable = true)
	private String comment;
	
	@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
	private Set<ExchangeAttribute> attributes = Sets.newHashSet();
	
	public void addAttribute(ExchangeAttribute attr) {
		attributes.add(attr);
	}
	
	@Transient
	public List<ExchangeAttribute> getAttributeList() {
		List<ExchangeAttribute> list = Lists.newArrayList(attributes);
		Collections.sort(list, new Comparator<ExchangeAttribute>() {

			@Override
			public int compare(ExchangeAttribute a1, ExchangeAttribute a2) {
				return a1.getRdm().compareTo(a2.getRdm());
			}
			
		});
		return list;
	}
	
	public static ExchangeMapping newExchangeMapping() {
		ExchangeMapping ex = new ExchangeMapping();
		return ex;
	}
}
